package com.zhuhjay.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;

/**
 * @author ZhuHJay
 * @date 2023/3/6 21:16
 */
public class RedisClient {
    /** Redis中 RESP 协议头 */
    private final static char SIMPLE_STRING = '+';
    private final static char ERRORS = '-';
    private final static char NUMBER = ':';
    private final static char MULTI_STRING = '$';
    private final static char ARRAY = '*';
    private final static String NEW_LINEAR = "\r\n";

    private final Channel channel;

    public RedisClient(String host, int port) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        channel = new Bootstrap()
                .channel(NioSocketChannel.class)
                .group(group)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                super.write(ctx, msg, promise);
                            }
                        });
                    }
                }).connect(host, port).sync().channel();
        channel.closeFuture().addListener((ChannelFutureListener) future -> group.shutdownGracefully());
    }

    /** 发送数据 **/
    public void send(String message) {
        String[] strings = message.split(" ");
        StringBuilder sb = new StringBuilder();
        sb.append(ARRAY).append(strings.length).append(NEW_LINEAR);
        for (String string : strings) {
            sb.append(MULTI_STRING).append(string.length()).append(NEW_LINEAR)
                    .append(string).append(NEW_LINEAR);
        }
        channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8)));
    }

    /** 关闭连接 **/
    public void close() {
        channel.close();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Scanner sc = new Scanner(System.in);
        RedisClient client = new RedisClient("localhost", 6379);
        while (true) {
            String command = sc.nextLine();
            if ("quit".equals(command)) {
                client.send(command);
                client.close();
                break;
            }
            client.send(command);
        }
    }
}
